package com.intellagric.service.sys_role;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.intellagric.common.bean.LayuiDataGridResult;
import com.intellagric.common.bean.ResponseMessage;
import com.intellagric.dao.sys_role.SysRoleDao;
import com.intellagric.interfaces.sys_role.RoleService;
import com.intellagric.mapper.*;
import com.intellagric.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @Auther: zhy
 * @Date: 2018/10/4
 * @Description: 角色管理服务
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleOperateMapper sysRoleOperateMapper;




    /**
     * 添加角色信息和对应的权限
     * @param sysRole
     * @return ResponseMessage
     */
    @Override
    public ResponseMessage addRole(SysRole sysRole) {
        if (sysRoleMapper.insertSelective(sysRole) == 1) {
            String roleId = sysRole.getId();
            //添加菜单权限信息
            String[] menuIds = sysRole.getMenuIds();
            if(menuIds!=null) {
                SysRoleMenuKey sysRoleMenuKey = new SysRoleMenuKey();
                for (String menuId : menuIds) {
                    sysRoleMenuKey.setRoleId(roleId);
                    sysRoleMenuKey.setMenuId(menuId);
                    sysRoleMenuMapper.insertSelective(sysRoleMenuKey);
                }
            }
            //添加操作权限信息
            String[] operateIds=sysRole.getOprateIds();
            if(operateIds!=null) {
                SysRoleOperateKey sysRoleOperateKey = new SysRoleOperateKey();
                for (String operateId : operateIds) {
                    sysRoleOperateKey.setOperateId(operateId);
                    sysRoleOperateKey.setRoleId(roleId);
                    sysRoleOperateMapper.insertSelective(sysRoleOperateKey);
                }
            }

            return ResponseMessage.success();
        } else {
            return ResponseMessage.fail();
        }
    }

    /**
     * 删除角色信息和对应的权限
     * @param id
     * @return ResponseMessage
     */
    @Override
    public ResponseMessage deleteRole(String id) {
        //删除角色权限信息

        SysRoleMenuExample sysRoleMenuExample = new SysRoleMenuExample();
        sysRoleMenuExample.createCriteria().andRoleIdEqualTo(id);
        sysRoleMenuMapper.deleteByExample(sysRoleMenuExample);

        SysRoleOperateExample sysRoleOperateExample = new SysRoleOperateExample();
        sysRoleOperateExample.createCriteria().andRoleIdEqualTo(id);
        sysRoleOperateMapper.deleteByExample(sysRoleOperateExample);

        //删除角色
        if (sysRoleMapper.deleteByPrimaryKey(id) == 1) {
            return ResponseMessage.success();
        } else {
            return ResponseMessage.fail();
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */

    @Override
    public ResponseMessage batchDelete(String[] ids) {

        //如果user_roel有对应的roleid数据，对应的user的角色就置为普通管理员 roleId= 2
        SysUserRoleExample sysUserRoleExample=new SysUserRoleExample();

        sysUserRoleExample.createCriteria().andRoleIdIn(Arrays.asList(ids));
        if(sysUserRoleMapper.countByExample(sysUserRoleExample)>0) {
            if (sysRoleDao.batchModifyUserRoleByRoleId(ids) < 1)
                return ResponseMessage.fail();
        }
        //删除role_menu对应数据
        if ( sysRoleDao.batchDeleteRoleMenuByRoleId(ids)<1)
            return ResponseMessage.fail();

        //删除role_operate对应的数据
        if ( sysRoleDao.batchDeleteRoleOperateByRoleId(ids)<1)
            return ResponseMessage.fail();


        if (sysRoleDao.batchDeleteByPrimaryKey(ids) <1)
            return ResponseMessage.fail();
        return ResponseMessage.success();
    }



    /**
     * 修改角色信息和对应的权限
     * @param sysRole
     * @return ResponseMessage
     */
    @Override
    public ResponseMessage editRole(SysRole sysRole) {
        String roleId = sysRole.getId();

        String[] menuIds = sysRole.getMenuIds();



            //删除角色原有的权限信息再添加
            SysRoleMenuExample sysRoleMenuExample = new SysRoleMenuExample();
            sysRoleMenuExample.createCriteria().andRoleIdEqualTo(sysRole.getId());
            sysRoleMenuMapper.deleteByExample(sysRoleMenuExample);
            //添加菜单权限信息

            SysRoleMenuKey sysRoleMenuKey = new SysRoleMenuKey();
        if(menuIds!=null) {
            for (int i = 0; i < menuIds.length; i++) {
                sysRoleMenuKey.setRoleId(roleId);
                sysRoleMenuKey.setMenuId(menuIds[i]);
                sysRoleMenuMapper.insertSelective(sysRoleMenuKey);
            }
        }
        String[] operateIds=sysRole.getOprateIds();


            SysRoleOperateExample sysRoleOperateExample = new SysRoleOperateExample();
            sysRoleOperateExample.createCriteria().andRoleIdEqualTo(sysRole.getId());
            sysRoleOperateMapper.deleteByExample(sysRoleOperateExample);
            //添加操作权限信息

            SysRoleOperateKey sysRoleOperateKey = new SysRoleOperateKey();
        if(operateIds!=null) {
            for (int i = 0; i < operateIds.length; i++) {
                sysRoleOperateKey.setOperateId(operateIds[i]);
                sysRoleOperateKey.setRoleId(roleId);
                sysRoleOperateMapper.insertSelective(sysRoleOperateKey);
            }
        }

        //修改角色信息
        if (sysRoleMapper.updateByPrimaryKeySelective(sysRole) == 1) {
            return ResponseMessage.success();
        }
        return ResponseMessage.fail();
    }

    /**
     * 查询角色信息和对应的权限
     * @param id
     * @return ResponseMessage
     */
    @Override
    public SysRole getRoleById(String id) {
        //查询角色信息
        SysRole role = sysRoleMapper.selectByPrimaryKey(id);

        //查询角色的菜单权限信息
        SysRoleMenuExample sysRoleMenuExample = new SysRoleMenuExample();
        sysRoleMenuExample.createCriteria().andRoleIdEqualTo(id);
        List<SysRoleMenuKey> menuKeys = sysRoleMenuMapper.selectByExample(sysRoleMenuExample);
        String[] menuIds = new String[menuKeys.size()];
        for (int i = 0;i < menuKeys.size();i++) {
            menuIds[i] = menuKeys.get(i).getMenuId();
        }
        role.setMenuIds(menuIds);

        //查询角色的操作权限信息
        SysRoleOperateExample sysRoleOperateExample = new SysRoleOperateExample();
        sysRoleOperateExample.createCriteria().andRoleIdEqualTo(id);
        List< SysRoleOperateKey> operateKeys = sysRoleOperateMapper.selectByExample(sysRoleOperateExample);
        String[] operateIds = new String[operateKeys.size()];
        for (int i = 0;i < operateKeys.size();i++) {
            operateIds[i] = operateKeys.get(i).getOperateId();
        }
        role.setOprateIds(operateIds);
        return role;
    }

    /**
     * 查询角色信息列表
     * @return ResponseMessage
     */
    @Override
    public LayuiDataGridResult getRoleList() {
        SysRoleExample sysRoleExample = new SysRoleExample();
        sysRoleExample.createCriteria().andIdIsNotNull();
        List<SysRole> roles = sysRoleMapper.selectByExample(sysRoleExample);
        return LayuiDataGridResult.success().add(roles,roles.size());
    }

    /**
     * 分页查询角色信息列表
     * @return ResponseMessage
     */
    @Override
    public LayuiDataGridResult getRoleList(int page, int rows,String keyword) {
        PageHelper.startPage(page, rows);


        SysRoleExample sysRoleExample = new SysRoleExample();
        if(keyword!=null&&keyword!="")
            sysRoleExample.createCriteria().andNameLike("%"+keyword+"%");
        else
            sysRoleExample.createCriteria().andIdIsNotNull();

        List<SysRole> roles = sysRoleMapper.selectByExample(sysRoleExample);

        PageInfo info=new PageInfo(roles);
        return LayuiDataGridResult.success().add(roles,info.getTotal());
    }

    /**
     * 通过角色id查询菜单列表信息,并生成菜单树
     * @return LayuiDataGridResult
     */
    @Override
    public LayuiDataGridResult getPermissionByRole(String id){
        //获取所有的角色的权限列表
        String[] menuIds = getRoleById(id).getMenuIds();
        List<SysMenu> menuList = new ArrayList<>();
        for (String menuId:menuIds) {
            SysMenu sysMen= sysMenuMapper.selectByPrimaryKey(menuId);
            menuList.add(sysMen);
        }

        //排序
        Collections.sort(menuList, new Comparator<SysMenu>() {
            @Override
            public int compare(SysMenu o1, SysMenu o2) {
                return o1.getSort() < o2.getSort() ? 1 : -1;//降序排列
            }
        });

        //查询其中的顶级分类
        List<SysMenu> rootMenuList = new ArrayList<>();
        for (SysMenu sysMenu: menuList) {
            if (sysMenu.getParentId().equals("0")) {
                rootMenuList.add(sysMenu);
            }
        }

        //生成树形菜单数据，为一级菜单设置子菜单，getChild是递归调用的
        for (SysMenu sysMenu : rootMenuList) {
            sysMenu.setChildren(getChild(sysMenu.getId(), menuList));
        }

        return LayuiDataGridResult.success().add(rootMenuList,rootMenuList.size());
    }

    private List<SysMenu> getChild(String id, List<SysMenu> menuList) {
        // 子菜单
        List<SysMenu> childList = new ArrayList<>();

        // 遍历所有节点，将父菜单id与传过来的id比较
        for (SysMenu sysMenu : menuList) {
            if (sysMenu.getParentId() != null) {   //所有非以及菜单的都要加入chidList中（递归）
                if (sysMenu.getParentId().equals(id)) {
                    childList.add(sysMenu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (SysMenu sysMenu : childList) {// 没有url子菜单还有子菜单（暂不考虑url的问题）
            // 递归
            sysMenu.setChildren(getChild(sysMenu.getId(), menuList));
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

}
